package com.voja.salonschedule.customers;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

import com.voja.AndroidUtils.Application;
import com.voja.salonschedule.Customers;
import com.voja.salonschedule.R;
import com.voja.salonschedule.customers.RemoteImage.RemoteImageParams;
import com.voja.salonschedule.data.Customer;
import com.voja.salonschedule.data.Customer.CustomerItem;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.ImageView;

public class PhotoOptionClickListener implements DialogInterface.OnClickListener{
    
    public static final String PHOTO_CROP = "com.android.camera.action.CROP";
    
    public static final int PHOTO_WIDTH  = 800;
    public static final int PHOTO_HEIGHT = 800;
    
    public static final int IMAGE_VIEWED   = 9991;
    public static final int IMAGE_REMOVED  = 9992;
    public static final int IMAGE_PICKED   = 9993;
    public static final int IMAGE_CAPTURED = 9994;
    public static final int IMAGE_CROPPED  = 9995;
    
    private Context      context;
    private static CustomerItem customer;
    
    private Intent intent = new Intent();
    private TmpFile tmpFile;
    private ArrayList<Integer> optionIds;
    
    public PhotoOptionClickListener(Context context, CustomerItem customer, 
                                    ArrayList<String> options, ArrayList<Integer> optionIds) {
        this.context   = context;
        PhotoOptionClickListener.customer  = customer;
        this.optionIds = optionIds;
        
        tmpFile = new TmpFile(context, Environment.DIRECTORY_PICTURES);
    }
    
    @Override
    public void onClick(DialogInterface dialog, int which) {
        
        switch(optionIds.get(which)) {
        
        // view
        case 0:
            view();
            break;
            
        // rotate left
        case 1:
            rotate(-90);
            break;
            
        // rotate right
        case 2:
            rotate(90);
            break;
            
        // remove
        case 3:
            remove();
            break;
            
        // from gallery
        case 4:
            pick();
            break;
            
        // capture
        case 5:
            capture();
            break;
        }
    }
    
    private void view() {
        Bitmap bm = customer.bitmap();
        if (bm != null) {
            tmpFile.write(customer.image);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(tmpFile.getUri(), "image/*");
            ((Activity)context).startActivityForResult(intent, IMAGE_VIEWED);
        }
    }
    
    private void rotate(int deg) {
        if (customer.image != null) {
            Bitmap bm = BitmapFactory.decodeByteArray(customer.image, 0, customer.image.length);
            Matrix m = new Matrix();
            m.postRotate(deg);
            
            Activity activity = (Activity)context;
            Bitmap bm2 = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
            customer.image = bytesFromBitmap(bm2);
            if (updateCustomer(activity, customer)) {
                ImageView image = ((ImageView)activity.findViewById(R.id.imgCustomer));
                image.setImageBitmap(bm2);
            }
        }
    }
    
    private void remove() {
        customer.image = null;
        updateCustomer((Activity)context, customer);
        Activity activity = (Activity)context;
        
        ImageView image = ((ImageView)activity.findViewById(R.id.imgCustomer));
        image.setImageResource(R.drawable.contact);
    }
    
    private void pick() {
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        intent.setData(MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        intent.putExtra("outputX", PHOTO_WIDTH);
        intent.putExtra("outputY", PHOTO_HEIGHT);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", true);
        intent.putExtra("scale", true);
        ((Activity)context).startActivityForResult(intent, IMAGE_PICKED);
    }
    
    private void capture() {
        tmpFile.create();
        intent.setAction(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpFile.getUri());
        ((Activity)context).startActivityForResult(intent, IMAGE_CAPTURED);
    }

    public static Bitmap handleRequest(Activity activity, int request, Intent intent) {
        Bitmap ret = null;
        switch (request) {
        case IMAGE_PICKED:
            imagePicked(activity, intent);
            break;
            
        case IMAGE_CAPTURED:
            imageCaptured(activity, intent);
            break;
            
        case IMAGE_CROPPED:
            ret = imageCropped(activity, intent);
            break;
        }
        
        return ret;
    }
    
    private static String getPathFromUri(Context context, Uri uri) {
        String path = null;
        String[] filePath = {MediaStore.Images.Media.DATA};
        Cursor c = context.getContentResolver().query(uri, filePath, null, null, null);
        if (c.moveToFirst()) {
            path = c.getString(0);
        }
       
        return path;
    }
    
    private static void crop(Activity activity) throws ActivityNotFoundException {
        TmpFile tmpFile = new TmpFile(activity, Customers.TYPE_PICTURES);
        tmpFile.create();
        
        Intent intent = new Intent(PHOTO_CROP);
        intent.setDataAndType(tmpFile.getUri(), "image/*")
            .putExtra("crop", true)
            .putExtra("aspectX", PHOTO_WIDTH)
            .putExtra("aspectY", PHOTO_HEIGHT)
            .putExtra("outputX", PHOTO_WIDTH)
            .putExtra("outputY", PHOTO_HEIGHT)
            .putExtra("scale", true)
            .putExtra("scaleUpIfNeeded", true)
            .putExtra("return-data", true);
        activity.startActivityForResult(intent, IMAGE_CROPPED);
    }
    
    private static void imagePicked(Activity activity, Intent intent) {
        Uri uri = intent.getData();
        String path = getPathFromUri(activity, uri);
        String errorMessage = activity.getResources().getString(R.string.errorPickingImage);
        if (path != null) {
            File f = new File(path);
            
            try {
                TmpFile tmpFile = TmpFile.getInstance(activity, Customers.TYPE_PICTURES);
                tmpFile.create();
                tmpFile.createOutputStream();
                
                // local file
                if (f.exists()) {
                    tmpFile.copyFromFile(f);
                    crop(activity);
                    
                // remote file
                } else {
                    RemoteImage image = new RemoteImage();
                    RemoteImageParams params = image.new RemoteImageParams(activity, path);
                    
                    Bitmap bm = image.execute(params).get();
                    if (bm != null) {
                        bm.compress(Bitmap.CompressFormat.JPEG, 100, tmpFile.getOutStream());
                        tmpFile.closeOutStream();
                        
                        crop(activity);
                    } else {
                        android.util.Log.e(activity.getClass().getName(), "not a bitmap");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                android.util.Log.e(e.getClass().getSimpleName(), "Error:"+e.getMessage());
            }
        } else {
            Application.alert(errorMessage);
        }
    }
    
    private static void imageCaptured(Activity activity, Intent intent) {
        crop(activity);
    }
    
    private static Bitmap imageCropped(Activity activity, Intent intent) {
        Bitmap bm = (Bitmap)intent.getExtras().get("data");
        if (bm != null) {
            customer.image = bytesFromBitmap(bm);
        } else {
            customer.image = null;
        }
        
        // update customer image
        if (updateCustomer(activity, customer)) {
            return bm;
        } else {
            return null;
        }
    }
    
    private static boolean updateCustomer(Activity activity, CustomerItem c) {
        Customer modelCustomer = new Customer(activity);
        return modelCustomer.update(c, c.name);
    }
    
    private static byte[] bytesFromBitmap(Bitmap bm) {
        ByteArrayOutputStream s = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, s);
        return s.toByteArray();
    }
}
 